import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/network/http_config.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

import 'account/account_modify.dart';

class LoginUi extends StatelessWidget {
  const LoginUi({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: _LoginPage(),
    );
  }
}

class _LoginPage extends StatefulWidget {
  const _LoginPage({Key? key}) : super(key: key);

  @override
  State createState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends State<_LoginPage> {
  // 登录按钮颜色选择器
  var _loginBtnSelector = [0xFFF5F6F6, 0xFF222222];
  final _loginBtnEnable = [0xFFFB6D99, 0xFFFFFFFF];
  final _loginBtnUnable = [0xFFF5F6F6, 0xFF222222];

  final _mobController = TextEditingController();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return SingleChildScrollView(
        child: SizedBox(
      width: size.width,
      height: size.height,
      child: Column(
        children: [
          // 标题
          Container(
            alignment: AlignmentDirectional.topStart,
            margin: const EdgeInsets.fromLTRB(20, 130, 0, 0),
            child: const Text(
              "欢迎登录都肆商圈ouran",
              style: TextStyle(fontSize: 30, color: Color(0xFF222222)),
            ),
          ),
          // 输入框
          Container(
            margin: const EdgeInsets.fromLTRB(20, 48, 20, 0),
            height: 45,
            child: TextField(
              controller: _mobController,
              maxLength: 11,
              keyboardType: TextInputType.phone,
              cursorColor: const Color(0xFFFB6D99),
              style: const TextStyle(fontSize: 18, color: Color(0xFF222222)),
              decoration: const InputDecoration(
                  hintText: "请输入手机号",
                  counterText: "",
                  border: InputBorder.none,
                  hintStyle: TextStyle(color: Color(0xFF999999)),
                  focusedBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Color(0xFFEBEBEB))),
                  enabledBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Color(0xFFEBEBEB)))),
              onChanged: (e) {
                setState(() {
                  _loginBtnSelector =
                      e.length >= 11 ? _loginBtnEnable : _loginBtnUnable;
                });
              },
            ),
          ),
          // 输入框小提示
          Container(
            padding:
                const EdgeInsets.symmetric(vertical: 12.0, horizontal: 20.0),
            child: const Text(
              "未注册的手机号验证后自动创建偶然遇见ouran账户",
              style: TextStyle(fontSize: 13, color: Color(0xFF999999)),
            ),
          ),
          // 登录按钮
          GestureDetector(
            child: Container(
                margin: const EdgeInsets.symmetric(
                    vertical: 12.0, horizontal: 20.0),
                height: 48,
                decoration: ShapeDecoration(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(24)),
                    color: Color(_loginBtnSelector[0])),
                width: double.maxFinite,
                child: Center(
                  child: Text(
                    "获取短信验证码",
                    style: TextStyle(
                        color: Color(_loginBtnSelector[1]), fontSize: 15),
                  ),
                )),
            onTap: () {
              _sendVerifyCode();
            },
          ),
          // 验证码登录、忘记密码
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              GestureDetector(
                child: Container(
                    margin: const EdgeInsets.only(left: 20.0),
                    height: 48,
                    child: const Center(
                      child: Text(
                        "验证码登录",
                        style:
                            TextStyle(fontSize: 13, color: Color(0xFF222222)),
                      ),
                    )),
                onTap: () {},
              ),
              GestureDetector(
                child: Container(
                    margin: const EdgeInsets.only(right: 20.0),
                    height: 48,
                    child: const Center(
                      child: Text(
                        "忘记密码",
                        style:
                            TextStyle(fontSize: 13, color: Color(0xFF222222)),
                      ),
                    )),
                onTap: () {
                  Navigator.of(context).push(MaterialPageRoute(
                      builder: (ctx) => const AccountModifyUi()));
                },
              ),
            ],
          ),
          Expanded(child: Container()),
          // 微信登录、协议
          Align(
            alignment: Alignment.bottomCenter,
            child: GestureDetector(
              child: const Image(
                width: 40,
                height: 40,
                image: AssetImage("images/ic_cwx.png"),
              ),
              onTap: () {
                _loginByWechat();
              },
            ),
          ),
          Container(
            padding: const EdgeInsets.fromLTRB(0, 30, 0, 20),
            child: Center(
                child: Text.rich(TextSpan(children: [
              const TextSpan(
                  text: "登录代表您已同意",
                  style: TextStyle(color: Color(0xFF222222), fontSize: 12)),
              TextSpan(
                text: "《用户协议》",
                style: const TextStyle(color: Color(0xFF222222), fontSize: 12),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    print('用户协议');
                  },
              ),
              TextSpan(
                text: "、《隐私政策》",
                style: const TextStyle(color: Color(0xFF222222), fontSize: 12),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    print('隐私政策');
                  },
              )
            ]))),
          )
        ],
      ),
    ));
  }

  void _getData() async {}

  _sendVerifyCode() {
    //   HttpConfig.token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsYXN0VGltZSI6MTY2MzM5MjczNSwibG9naW5JZCI6IjVmYzU0ZjIxZWNmMDQ2YzFiOWU5ZGEzZDFkNzcwNDgwIiwiZXhwIjoxNjYzNDEwNzM1LCJwaG9uZU5vIjoiMTUyMDExNjMyNzAiLCJtZW1iZXJJZCI6IjFjNDFkOTk4ZmJiMzRjZmFiNjQxZTU1MTkyOGVkNGRkIn0.LYVRIMKmeA2q2cxXGZ1QWavPOfVAJvpaZBWZUkhKL9Y";
    //   Provider.memberId = "1c41d998fbb34cfab641e551928ed4dd";
    //   Navigator.of(context).pushAndRemoveUntil(
    //     MaterialPageRoute(builder: (ctx) => const ProfileCompleteUi()),
    //     (route) => false
    // );

    if (_mobController.text.length != 11) {
      return;
    }
    loading(() async {
      final res = await Api.getInstance().loginSendCode(_mobController.text);
      if (res['code'] == 0) {
        if (res['data'] != null && res['data']['sig'] != null) {
          // Navigator.of(context).push(MaterialPageRoute(builder: (ctx) => LoginVerifyCode(_mobController.text, res['data']['sig']?? "",'','')));
        } else {
          ThemeSnackBar.show(context, "验证码发送失败");
        }
      } else {
        ThemeSnackBar.show(context, res['msg']);
      }
    });
  }

  _loginByWechat() async {
    ;
    final url =
        'https://open.weixin.qq.com/connect/oauth2/authorize?appid=${Provider.wechatAppID}&redirect_uri=${Uri.encodeComponent("${HttpConfig.baseUrl}#/")}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
    await launchUrl(Uri.parse(url));
  }
}
